package Change.webapp.action;

import java.util.List;

import Change.model.School;
import Change.service.SchoolManager;

import com.opensymphony.xwork2.Preparable;

public class SchoolAction extends BaseAction implements Preparable{
	

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Long id;
	private List<School> schools;
	private School school;
	private  SchoolManager schoolManager;
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public List<School> getSchools() {
		return schools;
	}

	public School getSchool() {
		return school;
	}

	public SchoolManager getSchoolManager() {
		return schoolManager;
	}

	public void setSchoolManager(SchoolManager schoolManager) {
		this.schoolManager = schoolManager;
	}

	public void setSchools(List<School> schools) {
		this.schools = schools;
	}

	public void setSchool(School school) {
		this.school = school;
	}

	public void prepare() throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	public String getAllSchools(){
		this.schools = schoolManager.getSchools();
		return SUCCESS;
	}
	
	
	public String delete(){
		if(id != null){
			schoolManager.remove(id);			
		}else{
			schoolManager.remove(school.getId());
		}
		saveMessage(getText("school.deleted"));
		return SUCCESS;
	}
	
	public String edit(){
		if(null != id){
			this.school = schoolManager.getSchool(id);
		}else{
			this.school = new School();
		}
		
		return SUCCESS;
	}
	
	public void prepareSave(){
		
		if(getRequest().getMethod().equalsIgnoreCase("post")){
			if("".equals(getRequest().getParameter("school.id"))){
				school = new School();
			}else{
				school = schoolManager.getSchool(
						Long.parseLong(getRequest().getParameter("schoo.id")));
			}
		}
	}
	
	public String save(){
		if(null != cancel){
			return CANCEL;
		}
		
		boolean isNew = (null == this.school.getId());
		school = schoolManager.save(school);
		String key = isNew ? "school.added" : "school.updated";
		saveMessage(getText(key));
		if (isNew){
			return SUCCESS;
		}else{
			return INPUT;
		}
	}

}
